package org.alvin.code.tools;

import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.List;

public class DateRangeUtils {

    /**
     * 按小时计算,分隔
     *
     * @param begin
     * @param end
     * @return
     */
    public static List<DateRange> splitDateRangeByHour(Date begin, Date end) {
        System.out.println("按小时切割");
        Calendar calendar = Calendar.getInstance();
        calendar.setTime(begin);
        List<DateRange> list = new ArrayList<>();
        DateRange range = new DateRange();
        range.setBegin(begin);
        while (true) {
            calendar.add(Calendar.HOUR_OF_DAY, 1);
            if (calendar.getTime().after(end)) {
                range.setEnd(end);
                list.add(range);
                break;
            }
            if (calendar.get(Calendar.HOUR_OF_DAY) == 23) {
                calendar.set(Calendar.MINUTE, 59);
                calendar.set(Calendar.SECOND, 59);
                calendar.set(Calendar.MILLISECOND, 0);
                range.setEnd(calendar.getTime());
                list.add(range);
                //第二天时间计算,并创建新的时间段
                calendar.add(Calendar.SECOND, 1);
                range = new DateRange();
                range.setBegin(calendar.getTime());
                continue;
            }
        }
        return list;
    }

    /**
     * 按天计算分隔(效率高 ,只超过一天有问题)
     *
     * @param begin
     * @param end
     * @return
     */
    public static List<DateRange> splitDateRangeByDay(Date begin, Date end) {
        System.out.println("按天切割");
        long time = end.getTime() - begin.getTime();
        if (time == 0) {
            return  new ArrayList<>();
        }
        long hours = time / (60 * 60 * 1000);
        if (time % (60 * 60 * 1000) > 0) {
            hours += 1;
        }
        if (hours <= 24) {
            return splitDateRangeByHour(begin, end);
        }
        Calendar calendar = Calendar.getInstance();
        calendar.setTime(begin);
        List<DateRange> list =  new ArrayList<>();
        DateRange range = new DateRange();
        range.setBegin(begin);
        while (true) {
            calendar.add(Calendar.DAY_OF_YEAR, 1);
            if (calendar.getTime().after(end)) {
                range.setEnd(end);
                list.add(range);
                break;
            }
            calendar.set(Calendar.HOUR_OF_DAY, 0);
            calendar.set(Calendar.MINUTE, 0);
            calendar.set(Calendar.SECOND, 0);
            calendar.set(Calendar.MILLISECOND, 0);
            //今天的开始
            Date tmpBeginTime = calendar.getTime();
            //计算出上一天的最后一秒
            calendar.add(Calendar.SECOND, -1);
            range.setEnd(calendar.getTime());
            list.add(range);
            //创建新的时间段
            range = new DateRange();
            range.setBegin(tmpBeginTime);
            //回到今天
            calendar.add(Calendar.SECOND, +1);
        }
        return list;
    }
}
